package cn.lg.soar.core.manager;

import cn.lg.soar.common.util.current.CurrentUser;
import cn.lg.soar.common.util.token.SoarJWT;

import java.util.Objects;

/**
 * 有状态token管理器
 * @author luguoxiang
 * @date 2022/4/4
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class StateTokenManager extends TokenManager{

    private final ITokenStateManager stateManager;

    public StateTokenManager(SoarJWT soarJWT, ITokenStateManager stateManager) {
        super(soarJWT);
        this.stateManager = stateManager;
    }

    /**
     * 创建token
     * @param refreshToken
     * @param clientSalt
     * @return accessToken
     */
    @Override
    public String create(String refreshToken, String clientSalt) {
        Object[] payload = SoarJWT.parsePayload(refreshToken, Object[].class);
        String token = soarJWT.create(payload, clientSalt);
        stateManager.put(payload[0].toString(), Long.parseLong(payload[1].toString()), soarJWT.expire);
        return token;
    }

    /**
     * 验证解析token，
     * @param accessToken token
     * @param clientSalt 客户端盐
     * @return 返回用户信息，验证失败返回null
     */
    @Override
    public CurrentUser getUserInfo(String accessToken, String clientSalt) {
        SoarJWT.Result verify = soarJWT.verify(accessToken, clientSalt);
        if (verify.invalid()) {
            return null;
        }
        Object[] payload = verify.getPayload(Object[].class);
        Long value = stateManager.get(payload[0].toString());
        if (Objects.equals(Long.parseLong(payload[1].toString()), value)) {
            return CurrentUser.valueOf(payload);
        }
        return null;
    }

    /**
     * 删除token状态
     * @param accessToken token
     * @param clientSalt 客户端盐
     */
    public void remove(String accessToken, String clientSalt) {
        SoarJWT.Result verify = soarJWT.verify(accessToken, clientSalt);
        if (verify.invalid()) {
            return;
        }
        Object[] payload = verify.getPayload(Object[].class);
        remove(payload[0].toString(), Long.parseLong(payload[1].toString()));
        Long value = stateManager.get(payload[0].toString());
    }

    /**
     * 删除token状态
     * @param id tokenId
     * @param value tokenValue
     */
    public void remove(String id, Long value) {
        Long valueOld = stateManager.get(id);
        if (Objects.equals(valueOld, value)) {
            stateManager.remove(id);
        }
    }

}
